from app import db
from app.models.book import Book, BookSchema

book_schema = BookSchema()
books_schema = BookSchema(many=True)


def get_all_books():
    return books_schema.dump(db.session.execute(db.select(Book)).scalars())


def get_book_by_id(book_id):
    return book_schema.dump(db.get_or_404(Book, book_id))


def add_book(data):
    book = Book(**data)
    db.session.add(book)
    db.session.commit()


def delete_book(book_id):
    book = db.get_or_404(Book, book_id)

    db.session.delete(book)
    db.session.commit()


def update_book(request_data):
    book = db.get_or_404(Book, request_data['book_id'])

    if book:
        book.book_name = request_data['book_name']
        book.author = request_data['author']
        book.category_id = request_data['category_id']
        book.description = request_data['description']

        db.session.commit()
